package 力扣_排序算法.对Map中的value排序;

import java.util.*;

/**
 * @author zx
 * @create 2022-08-29 11:31
 */
public class 根据字符出现频率排序_451 {
    /**
     * @return 对map中的value进行排序
     */
    public String frequencySort(String s) {
        LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
        for(int i = 0;i < s.length();i++){
            map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0) + 1);
        }
        List<Map.Entry<Character,Integer>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        String res = "";
        for(int i = 0;i < entries.size();i++){
            int count = entries.get(i).getValue();
            while(count > 0){
                res += entries.get(i).getKey();
                count--;
            }
        }
        return res;
    }
}
